<template>
  <div id="favorite-page">
    <h3 class="search">
      搜索:
      <el-input
        v-model="input"
        style="width: 240px; margin: 0 1em"
        placeholder="请输入音乐名称"
      />
      <el-button
        type="success"
        @click="search()"
        >搜索
      </el-button>
      <el-button
        type="primary"
        @click="
          () => {
            input = ''
            initUserFavorites()
          }
        "
        >重置
      </el-button>
    </h3>
    <RankItem
      class="rank-item"
      v-for="(item, index) in favorites?.records"
      :key="index"
      :songsVO="item"
    ></RankItem>
    <div class="page">
      <el-pagination
        layout="prev, pager, next"
        v-model:current-page="currentPage"
        @update:current-page="initUserFavorites(currentPage)"
        :total="pageTotal"
        :size="'large'"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { PageDTO, SongsPageDTO, SongsPageInfo } from '@/types/song'
import { useUserStore } from '@/stores/userStore.ts'
import RankItem from '@components/RankItem.vue'
import { SortBy, SortOrder } from '@/utils/common/enum.ts'
import type { UnifyResponse } from '@/types/result'
import { getUserFavoritesAPI } from '@/services/songService.ts'

const favorites = ref<PageDTO<SongsPageDTO[]> | null>()
const userStore = useUserStore()
const currentPage = ref()
const input = ref('')
const pageTotal = ref(0)

const search = () => {
  if (!favorites.value) return
  const tempList = favorites.value?.records.filter(item => {
    return item.name?.includes(input.value)
  })
  favorites.value.records = tempList || []
  pageTotal.value = tempList?.length || 0
}

const initUserFavorites = async (page?: number) => {
  try {
    const data: SongsPageInfo = {
      page: page || 1,
      size: 10,
      sortBy: SortBy.CREATED,
      sortOrder: SortOrder.ASC,
    }
    const res: UnifyResponse<PageDTO<SongsPageDTO[]>> = await getUserFavoritesAPI(data)
    if (res.code === 200) {
      favorites.value = res.data || null
    }
    useUserStore().favoriteList = favorites.value || null
    pageTotal.value = favorites.value?.total || 0
    currentPage.value = page || 1
  } catch (e) {
    console.error(e)
  }
}

onMounted(() => {
  initUserFavorites()
  if (userStore.token && userStore.favoriteList) {
    favorites.value = userStore.favoriteList
  }
})
</script>

<style scoped>
#favorite-page {
  width: 42em;
  margin: 0 auto;
}

.rank-item {
  margin-top: 1em;
}

.page {
  display: flex;
  justify-content: center;
  margin-top: 1em;
}

.page:deep(.el-pagination button) {
  background-color: transparent;
}

.page:deep(.el-pager li) {
  background-color: transparent;
}

.search {
  margin-top: 1em;
}
</style>
